package service

import (
	"barrage-go/consts"
	"barrage-go/models"
	"barrage-go/proto/pb"
	"barrage-go/utils"
	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
)

func WebClientBarrageMsgRollingReq(msg []byte, ws *websocket.Conn) {

	rollingReq := pb.WebClientBarrageMsgRollingReq{}
	err := proto.Unmarshal(msg, &rollingReq)
	if err != nil {
		log.Println("解析滚动弹幕出现异常:", err)
		return
	}

	videoId := rollingReq.VideoId
	videoTime := rollingReq.CurrentVideoTime
	rollings := models.GetBarrageRollings(videoId, videoTime)

	rollingResp := pb.WebClientBarrageMsgRollingResp{}
	var barrageMsgList []*pb.BarrageHistoryMessage
	for _, v := range rollings {
		message := pb.BarrageHistoryMessage{}
		message.Msg = v.MsgContent
		message.MsgColor = v.MsgColor
		message.MsgPosition = v.MsgPosition
		message.SendTime = utils.SecToStrTime(v.VideoTime)
		message.VideoId = strconv.FormatInt(v.VideoId, 10)
		message.UserId = strconv.FormatInt(v.UserId, 10)
		message.CreateTime = v.CreateTime.Format("01-02 15:04")
		barrageMsgList = append(barrageMsgList, &message)
	}
	rollingResp.List = barrageMsgList

	rollingBytes, _ := proto.Marshal(&rollingResp)
	clientResp := pb.Barrage{
		MsgType:   consts.WebClientBarrageMsgRollingResp,
		BytesData: rollingBytes,
	}

	client, _ := proto.Marshal(&clientResp)
	err = ws.WriteMessage(websocket.BinaryMessage, client)

	if err != nil {
		log.Println("返回给客户端滚动弹幕消息发生异常:", err)
	}

}
